Date.prototype.format = function (fmt) { //author: meizz
 var o = {
     "M+": this.getMonth() + 1, //月份
     "d+": this.getDate(), //日
     "h+": this.getHours(), //小时
     "m+": this.getMinutes(), //分
     "s+": this.getSeconds(), //秒
     "q+": Math.floor((this.getMonth() + 3) / 3), //季度
     "S": this.getMilliseconds() //毫秒
 };
 if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
 for (var k in o)
 if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
 return fmt;
};
!(function(window,console,undefined){
 window.hxim = function(){
     var conn = new WebIM.connection({
         https: WebIM.config.https,
         url: WebIM.config.xmppURL,
         isAutoLogin: WebIM.config.isAutoLogin,
         isMultiLoginSessions: WebIM.config.isMultiLoginSessions
     });
     this.conn = conn;
     var that = this;
     this.options = {
        defaultAvater:'/image/avater.jpg',  // 默认头像
        messageBoxId:'im-messages',
        accId:'',
        token:'',
        avater:'',  // 用户头像地址存cookie中的key
        islogin:false
     };
     var userInfo = localStorage.imUserInfo;
     if(userInfo){
         var _info = JSON.parse(userInfo);
         this.options.accId = _info.accId;
         this.options.token = _info.token;
         this.options.avater = _info.avater;
     }
     conn.listen({
         onOpened:function(message){
             that.options.islogin = true;
             console.log('链接成功');
         },
         onClosed:function(){
             console.log("断开");
         },
         onTextMessage:function(message){
             var _avater = message.avater;
             if(_avater == "" || _avater == undefined){
                 _avater = that.options.defaultAvater;
             }
             that.appendMessageItem(false,message.from,_avater,message.messageId,message.data);
             console.log('收到文本消息');
         },
         onEmojiMessage:function(message){
             var _avater = message.avater;
             if(_avater == "" || _avater == undefined){
                 _avater = that.options.defaultAvater;
             }
             var res = "";
             for(var i = 0 ; i < message.data.length; i ++){
                 var item = message.data[i];
                 res += ((item.type == 'txt') ? item.data :('<img src="'+item.data+'" />'));
             }
             that.appendMessageItem(false,message.from,_avater,message.messageId,res);
             console.log('收到emoji消息');
         },
         onPictureMessage:function(message){
             var _avater = message.avater;
             if(_avater == "" || _avater == undefined){
                 _avater = that.options.defaultAvater;
             }
             var msg = '<img src="'+message.url+'" />';
             that.appendMessageItem(false,message.from,_avater,message.messageId,msg);
             console.log('收到图片消息');
         },
         onOnline:function(){
             console.log('onOnline');
         },
         onError:function(errorm){
             console.error(errorm);
         }
     });

     this.sendText = function(to,_msge,_success,_error){
         if(!that.options.islogin){
             alert('请先登录');
         }
         var id = conn.getUniqueId();
         var msg = new WebIM.message('txt', id);// 创建文本消息
         msg.set({
             msg:_msge,to:to,roomType: false,
             success: function (id, serverMsgId) {
                 _success(id,serverMsgId);
                 that.appendSelfMessage(serverMsgId,_msge);
                 console.log("消息发送成功");
             },
             fail: function(){
                 try{_error();}catch(e){}
             }
         });
         msg.body.chatType = 'singleChat';
         conn.send(msg.body);
     };
     this.appendSelfMessage = function(messageId,msg){
         if(that.options.avater == ""){
             _avater = this.options.defaultAvater;
         }
         this.appendMessageItem(true,'',_avater,messageId,msg);
     };
     this.appendMessageItem = function(me,auther,_avater,messageId,msg){
         var _msg = this.emojiHander(msg);
         var time = new Date().format("yyyy-MM-dd hh:mm:ss");
         var html = '<li id="messageItem'+messageId+'" class="'+(me?'message-right':'message-left')+'">'+
             '<img class="send-avater" src="'+_avater+'" />'+
             '<div class="send-tips">'+(me?(time +'&nbsp;&nbsp;'+auther):(auther+'&nbsp;&nbsp;'+time))+'</div>'+
             '<div class="send-message">'+_msg+'</div>'+
         '</li>';
         var msgbox = document.getElementById(this.options.messageBoxId);
         msgbox.innerHTML = msgbox.innerHTML + html;
         msgbox.scrollTop = msgbox.scrollHeight;
     };
     this.emojiHander = function(msg){
         var expr = /\[[^[\]]{2,3}\]/mg;
         var emotions = msg.match(expr);
         if ( !emotions || emotions.length < 1 ){
             return msg;
         }
         var result = msg;
         for(var i = 0 ;i < emotions.length;i++){
             var imgsrc = window.WebIM.Emoji.path +window.WebIM.Emoji.map[emotions[i]];
             result = result.replace(emotions[i],'<img src='+imgsrc+' />');
         }
         return result;
     }
     this.login = function(username,password,_avater,_success,_error){
        conn.open({
            apiUrl: WebIM.config.apiURL,
            user: username,
            pwd: password,
            appKey: WebIM.config.appkey,
            success: function (token) {
                var token = token.access_token;
                // 存储本地缓存
                window.localStorage.imUserInfo = '{"accId":"'+username+'","token":"'+token+'","avater":""}';
                try{_success(token)}catch(e){};
            },
            error: function(){
                try{_error()}catch(e){}
            }
        });
     };
     console.log(this.options);
     if(this.options.accId != "" && this.options.token != ""){
         console.log("-------------------");
         conn.open({ // 自动登录
             apiUrl: WebIM.config.apiURL,
             user: that.options.accId,
             accessToken:that.options.token,
             appKey: WebIM.config.appkey
         });
     }
 };
 window.WebIM = {
     config:{
         xmppURL: 'im-api.easemob.com',
         apiURL: (location.protocol === 'https:' ? 'https:' : 'http:') + '//a1.easemob.com',
         appkey: '1145170523178774#jcgsfc-test',
         https: false,
         isMultiLoginSessions: true,
         isAutoLogin: true,
         isWindowSDK: false,
         isSandBox: false,
         isDebug: false,
         autoReconnectNumMax: 2,
         autoReconnectInterval: 2,
         isWebRTC: (/Firefox/.test(navigator.userAgent) || /WebKit/.test(navigator.userAgent)) && /^https\:$/.test(window.location.protocol),
         heartBeatWait: 4500,
         isHttpDNS: false,
         msgStatus: true,
         delivery: true,
         read: false,
         encrypt: {
             type: 'none'
         }
     },
     Emoji:{
         path: '/image/faces/',
         map: {
             '[):]': 'ee_1.png',
             '[:D]': 'ee_2.png',
             '[;)]': 'ee_3.png',
             '[:-o]': 'ee_4.png',
             '[:p]': 'ee_5.png',
             '[(H)]': 'ee_6.png',
             '[:@]': 'ee_7.png',
             '[:s]': 'ee_8.png',
             '[:$]': 'ee_9.png',
             '[:(]': 'ee_10.png',
             '[:\'(]': 'ee_11.png',
             '[:|]': 'ee_12.png',
             '[(a)]': 'ee_13.png',
             '[8o|]': 'ee_14.png',
             '[8-|]': 'ee_15.png',
             '[+o(]': 'ee_16.png',
             '[<o)]': 'ee_17.png',
             '[|-)]': 'ee_18.png',
             '[*-)]': 'ee_19.png',
             '[:-#]': 'ee_20.png',
             '[:-*]': 'ee_21.png',
             '[^o)]': 'ee_22.png',
             '[8-)]': 'ee_23.png',
             '[(|)]': 'ee_24.png',
             '[(u)]': 'ee_25.png',
             '[(S)]': 'ee_26.png',
             '[(*)]': 'ee_27.png',
             '[(#)]': 'ee_28.png',
             '[(R)]': 'ee_29.png',
             '[({)]': 'ee_30.png',
             '[(})]': 'ee_31.png',
             '[(k)]': 'ee_32.png',
             '[(F)]': 'ee_33.png',
             '[(W)]': 'ee_34.png',
             '[(D)]': 'ee_35.png'
         }
     }
 };
})(window,window.console);
